<template>
    <div>
        <button @click="doAdd">添加</button>
        <TableCom :list="list">
        <template #table="{row}">
            <td>{{ row.id }}</td>
          <td>{{ row.bookname }}</td>
          <td>{{ row.author }}</td>
          <td>{{ row.publisher }}</td>
          <td><button @click="doEdit(row)">编辑</button><button @click="doDel(row)">删除</button></td>
        </template>
        </TableCom>
        <Dialog v-show="showDialog" :isEdit="isEdit" :showDialog.sync="showDialog" @handleBook="handleBook">
        <form>
        bookname: <input type="text" v-model="formData.bookname"> <br/>
        author: <input type="text" v-model="formData.author"> <br/>
        publisher: <input type="text" v-model="formData.publisher"> <br/>
      </form>
    </Dialog>
    </div>
</template>

<script>
import Dialog from './ShowDialog.vue'
import TableCom from './TableCom.vue'
import axios from 'axios'
export default {
  name: 'Books1Index',
  components: {
    Dialog, TableCom
  },
  data () {
    return {
      list: [],
      showDialog: false,
      formData: {
        bookname: '',
        author: '',
        publisher: ''
      },
      isEdit: true,
      bookid: ''
    }
  },
  created () {
    this.randerList()
  },
  mounted () {

  },

  methods: {
    // 渲染数据页面函数
    async randerList () {
      const res = await axios({
        url: 'http://ajax-api.itheima.net/api/books'
      })
      this.list = res.data.data
    },
    // 添加图书
    doAdd () {
      this.isEdit = true
      this.showDialog = true
    },
    async handleBook () {
      if (!this.formData.bookname.trim()) return alert('bookname不能为空')
      if (!this.formData.author.trim()) return alert('author不能为空')
      if (!this.formData.publisher.trim()) return alert('publisher不能为空')
      this.isEdit ? await this.handleAdd() : await this.putBook()
      await this.randerList()
      this.showDialog = false
    },
    // 添加图书
    async handleAdd () {
      await axios({
        url: 'http://ajax-api.itheima.net/api/books',
        method: 'post',
        data: this.formData
      })
      this.formData = {
        bookname: '',
        author: '',
        publisher: ''
      }
    },
    // 编辑图书
    doEdit (row) {
      this.showDialog = true
      this.isEdit = false
      this.bookid = row.id
      this.formData = JSON.parse(JSON.stringify(row))
    },
    async putBook () {
      const res = await axios({
        url: `http://ajax-api.itheima.net/api/books/${this.bookid}`,
        method: 'put',
        data: this.formData
      })
      console.log(res)
    },
    // 删除图书
    async doDel (item) {
      if (confirm(`确认删除${item.bookname}吗?`)) {
        await axios({
          url: `http://ajax-api.itheima.net/api/books/${item.id}`,
          method: 'delete'
        })
      }
      await this.randerList()
    }
  }
}
</script>

<style scoped>
button {
    width: 40px;
    height: 40px;
    background-color: greenyellow;
}
</style>
